package com.qq.client.model;

import com.qq.client.tools.JsonUtils;
import com.qq.client.view.QqFriendList;
import com.qq.common.Friend;
import com.qq.common.Message;
import com.qq.common.MessageType;

import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClientConServerThread extends Thread {
    private Socket socket;

    public ClientConServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            try {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Message m = (Message) ois.readObject();
                //返回好友列表
                if (MessageType.message_ret_onLineFriend.equals(m.getMesType())) {
                    System.out.println("客户端接收到" + m.getCon());
                    String con = m.getCon();
                    List<Map<String, String>> list = JsonUtils.jsonToObject(con, List.class);
                    String getter = m.getGetter();
                    List<Friend> friends = new ArrayList<>();
                    for (Map<String, String> map : list) {
                        Friend friend = new Friend();
                        friend.setNo(map.get("no"));
                        friend.setId(map.get("id"));
                        friend.setName(map.get("name"));
                        friend.setType(map.get("type"));
                        friend.setOnLine(map.get("onLine"));
                        friends.add(friend);
                    }
                    System.out.println("getter=" + getter);
                    //修改相应的好友列表.
                    QqFriendList qqFriendList = ManageQqFriendList.getQqFriendList(getter);
                    //	if(qqFriendList)
                    //更新在线好友.
                    if (qqFriendList != null) {
                        qqFriendList.loadFriendList(friends);
                    }
                } else if(MessageType.message_comm_mes.equals(m.getMesType())){
                    ManageQqChat.getQqChat(m.getGetter()+"_"+m.getSender()).showMessage(m);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }
}
